﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using Android.OS;
using Android.Views;
using AndroidX.Fragment.App;
using AndroidX.RecyclerView.Widget;
using AppExample.Adapters;
using AppExample.Models;
using Newtonsoft.Json;

namespace AppExample
{
    public class GirlFragment : Fragment
    {
        List<Girl> _girls = new List<Girl>();
        GirlAdapter _adapter;
        bool _isLoading = true;

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = inflater.Inflate(Resource.Layout.fragment_girl, container, false);
            var layoutManager = new LinearLayoutManager(Context);
            var rvGirl = view.FindViewById<RecyclerView>(Resource.Id.rvGirl);
            rvGirl.SetLayoutManager(layoutManager);
            rvGirl.HasFixedSize = true;

            _adapter = new GirlAdapter(_girls);
            rvGirl.SetAdapter(_adapter);
            var scrollListener = new OnScrollListener();
            scrollListener.LoadMoreEvent += (s, e) =>
            {
                if (!_isLoading)
                {
                    _isLoading = true;
                    GetImages();
                }
            };
            rvGirl.AddOnScrollListener(scrollListener);

            GetImages();

            return view;
        }

        async void GetImages()
        {
            var page = _girls.Count / 10 + 1;

            using var http = new HttpClient();
            http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");
            var response = await http.GetStringAsync($"http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/{page}");
            var json = JsonConvert.DeserializeObject<Gank>(response);
            if (json.Error == false)
            {
                _girls.AddRange(json.Results);
                _adapter.NotifyItemRangeInserted((page - 1) * 10, page * 10 - 1);
            }

            _isLoading = false;

        }

        class OnScrollListener : RecyclerView.OnScrollListener
        {
            public Action<object, EventArgs> LoadMoreEvent;

            public override void OnScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                if (recyclerView.GetLayoutManager() is LinearLayoutManager lm)
                {
                    var lastPostion = lm.FindLastVisibleItemPosition();
                    if (newState == RecyclerView.ScrollStateIdle && lastPostion == recyclerView.GetAdapter().ItemCount - 1)
                    {
                        LoadMoreEvent?.Invoke(recyclerView, null);
                    }
                }

            }
        }
    }
}